package com.jt.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class HttpClientService {
	@Autowired
	private CloseableHttpClient httpClient;
	@Autowired
	private RequestConfig requestConfig;

	/**
	 *  需求:给定url地址,则可以自动的发起请求,并且将返回值结果返回给用户.	
	 * 参数分析:
	 * 	1.用户的url参数地址
	 * 	2.判断用户是否需要携带参数   使用Map集合封装数据.
	 * 	3.指定字符集编码  需要用户自己指定
	 * 返回值: String类型
	 */
	public String doGet(String url,Map<String,String> params,String charset) {

		//1.判断用户是否传递字符集编码
		if(StringUtils.isEmpty(charset)) {

			//设定默认值
			charset = "UTF-8";
		}

		/**
		 * 2.判断用户是否携带参数
		 * 	 没有带参数: http://manage.jt.com/item
		 * 	 带参数: http://manage.jt.com/item?id=1&name=xxxx&;
		 * 	
		 * 	补充知识: entry={key=value}   Map~~~>entry~~~~~key:value
		 */
		if(params !=null) {//如果参数不为null,则需要进行参数拼接.
			url += "?";
			//map集合遍历. 从中动态的获取key=value.
			for (Map.Entry<String,String> entry : params.entrySet()) {
				String key = entry.getKey().trim();	//去除多余的空格
				String value = entry.getValue().trim();
				url += key+"="+value+"&";
			}
			//去除多余的&符
			url =url.substring(0, url.length()-1);
		}

		//3.定义请求对象
		HttpGet httpGet = new HttpGet(url);
		//添加超时配置
		httpGet.setConfig(requestConfig);
		//4.发起请求
		try {
			HttpResponse httpResponse = httpClient.execute(httpGet);
			//5.判断用户的请求是否正常
			if(httpResponse.getStatusLine().getStatusCode()==200) {
				//6.动态获取返回值
				return EntityUtils.toString(httpResponse.getEntity());
			}
			int status = httpResponse.getStatusLine().getStatusCode();
			throw new RuntimeException("获取后台错误的状态码:"+status+"|请求路径为:url"+url);
		} catch (IOException e) {
			e.printStackTrace();
			//将检查异常,转化为运行时异常
			throw new RuntimeException(e);
		}
	}
	public String doGet(String url) {
		return doGet(url, null, null);
	}
}
